package com.example.secondhandspringboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.entity.Contacts;
import com.example.secondhandspringboot.domain.vo.ContactVO;
import com.example.secondhandspringboot.exception.BaseException;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.IContactsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周在林
 * @since 2024-05-16
 */
@RestController
@RequestMapping("/contacts")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin
public class ContactsController {

    private final IContactsService contactsService;

    /**
     * 获取联系人列表
     * @return
     */
    @GetMapping("/getContacts")
    public Result<List<ContactVO>> getContacts(){
        log.info("获取联系人列表");
        List<ContactVO> contactVOList = contactsService.getContactsVOList();
        return Result.success(contactVOList);
    }

    /**
     * 创建联系人
     * @param contactUserId
     * @return
     */
    @PostMapping("/{contactUserId}")
    public Result createContact(@PathVariable Long contactUserId){
        log.info("创建联系人");
        if (contactUserId == null){
            throw new BaseException("contactUserId为空");
        }
        Long currentUserId = BaseContext.getCurrentId();
        if (Objects.equals(currentUserId, contactUserId)){
            return Result.error("不能联系自己哦");
        }
        Contacts contacts = contactsService.getContactBySendAndReceiveId(currentUserId,contactUserId);
        if (contacts==null){
            Contacts contact = new Contacts();
            contact.setContactUserId(contactUserId);
            contact.setUserId(currentUserId);
            contact.setCreateTime(LocalDateTime.now());
            contactsService.save(contact);
        }
        return Result.success();
    }


    /**
     * 删除联系人
     * @param contactUserId
     * @return
     */
    @DeleteMapping("/{contactUserId}")
    public Result deleteContacts(@PathVariable Long contactUserId){
        log.info("删除联系人");
        // 获取当前用户id
        Long currentId = BaseContext.getCurrentId();
        //删除联系人
        contactsService.remove(new LambdaQueryWrapper<>(Contacts.class)
                .eq(Contacts::getContactUserId,contactUserId)
                .eq(Contacts::getUserId,currentId));
        //删除与当前联系人消息
//        Db.remove(new LambdaQueryWrapper<>())
        return Result.success();
    }

}
